package redlock

import (
	"strconv"
	"time"

	"chat.com/pkg/cache"
	"github.com/bwmarrin/snowflake"
)

var snowflaker *snowflake.Node

func init() {
	var st time.Time
	st, err := time.Parse("2006-01-02", "2023-11-29")
	if err != nil {
		panic(err)
	}
	snowflake.Epoch = st.UnixNano() / 1000000
	snowflaker, err = snowflake.NewNode(10)
	return
}

func RedLock(lockName string, expiration time.Duration) (int64, bool) {
	uniqueVal := snowflaker.Generate().Int64()
	lock, err := cache.Rdb.SetNX(lockName, uniqueVal, expiration)
	if !lock || err != nil {
		return uniqueVal, false
	}

	return uniqueVal, true
}

func RedUnLock(lockName string, uniqueVal int64) bool {
	res, err := cache.Rdb.Get(lockName)
	if err != nil && err != cache.Nil {
		return false
	}

	if err == cache.Nil {
		return true
	}

	val, _ := strconv.ParseInt(res, 10, 64)

	if uniqueVal != val {
		return false
	}

	if _, err := cache.Rdb.Del(lockName); err != nil && err != cache.Nil {
		return false
	}

	return true
}
